// pages/addressinfo/addressinfo.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userList: []
  },
  goToEdit(e) {
    wx.navigateTo({
      url: '/pages/addAddress/addAddress?id=' + e.currentTarget.dataset.id,
    })
  },
  checkedAddress(e) {
    wx.setStorageSync('id', e.currentTarget.dataset.id)
    let userList = this.data.userList
    for(let i = 0;i<userList.length;i++){
      if(i==e.currentTarget.dataset.index){
        this.updateState(userList[i]._id,true)
        userList[i].state=true
      }else{
        this.updateState(userList[i]._id,false)
        userList[i].state=false
      }
    }
    this.setData({
      userList:userList
    })
    wx.showToast({
      title: '切换地址成功',
    })
  },
  updateState(id,state){
    wx.cloud.database().collection('location_list').doc(id).update({
      data: {
        state: state
      },
      success: function (res) {
        console.log("成功")
      }
    })
  },
  addAddress() {
    wx.navigateTo({
      url: '/pages/addAddress/addAddress',
    })
  },

  removeAddress(e) {
    // console.log(e.currentTarget.dataset.id);
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success:res => {
        if (res.confirm) {
          wx.cloud.database().collection('location_list')
            .doc(e.currentTarget.dataset.id) // 填写要删除条件的 _id
            .remove() // 删除数据
            .then(res => {
              console.log('删除成功', res);
              wx.showToast({
                title: '删除地址成功',
              })
              this.getData()
            })
            .catch(err => {
              console.error('删除失败', err);
            })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  getData() {
    const db = wx.cloud.database()
    db.collection('location_list').get({
      success: (res) => {
        console.log('请求成功', res.data);
        this.setData({
          userList: res.data
        })
      },
      fail: err => {
        console.log('请求失败', err);
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    console.log('ok');
    this.getData();
  },
})